package com.sinder.campus_prophet.core.interceptor;

import com.alibaba.fastjson.JSON;

import com.sinder.campus_prophet.core.global.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器");
        //获取请求头信息
        String usessionid = request.getHeader("USESSIONID"); // 获取sessionId是否存在
        // 判断是否登录 不为空表示有数据
        HttpSession session = request.getSession();
        //判断usessionid是否为空
        if (StringUtils.hasLength(usessionid) && session.getAttribute(usessionid) != null) {
            return true;
        }
        //token为空时返回错误信息
        setReturn(request, response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("MyInterceptor1 => postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("MyInterceptor1 => afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    //返回错误信息
    private static void setReturn(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Referer,User-Agent,ticket,loginId,loginTerminal,cityCode,source");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        try {
            httpServletResponse.getWriter().write(JSON.toJSONString(ResponseMessage.createByErrorCodeMessage(40005, "请先登录再操作")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
